package com.turbo.cloud.core.security.authentication;

import cn.hutool.core.util.StrUtil;
import com.turbo.cloud.core.security.jwt.JwtProperties;
import com.turbo.cloud.core.security.utils.SecurityUtil;
import com.turbo.cloud.core.security.jwt.JwtPayload;
import com.turbo.cloud.core.security.jwt.JwtUtils;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Objects;

/**
 * JWT登录授权过滤器
 *
 * @author zhangluning
 */
@Slf4j
public class JwtAuthTokenFilter extends OncePerRequestFilter {

    private JwtProperties jwtProperties;

    public JwtAuthTokenFilter(JwtProperties jwtProperties) {
        this.jwtProperties = jwtProperties;
        String accessTokenHeader = jwtProperties.getAccessTokenHeader();
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        String accessTokenHeader = jwtProperties.getAccessTokenHeader();
        String refreshTokenHeader = jwtProperties.getRefreshTokenHeader();
        String tokenHead = jwtProperties.getTokenHead();
        String secret = jwtProperties.getSecret();
        Long expiration = jwtProperties.getExpiration();
        Long advance = jwtProperties.getAdvance();

        String authHeader = request.getHeader(accessTokenHeader);
        if (StrUtil.isNotBlank(authHeader) && authHeader.startsWith(tokenHead)) {
            // The part after "Bearer " 有个空格
            String authToken = authHeader.substring(tokenHead.length());
            JwtPayload<AdminUser> jwtPayload = JwtUtils.getUserInfoFromToken(authToken, secret, AdminUser.class);
            AdminUser adminUser = jwtPayload.getUserInfo();
            log.debug("checking user:{}", adminUser);

            if (Objects.nonNull(adminUser) && SecurityContextHolder.getContext().getAuthentication() == null) {
                // 验证JWT Token的正确性和是否失效
                if (JwtUtils.validateTokenExpire(authToken, secret)) {
                    // 验证能否刷新JWT Token，放入http返回头中
                    if (JwtUtils.canRefreshTokenExpire(authToken, secret, advance)) {
                        response.setHeader(refreshTokenHeader, tokenHead + JwtUtils.refreshTokenExpire(authToken, adminUser, secret, expiration, advance));
                    }
                    // 验证JWT Token通过，要放入SpringSecurity中
                    SecurityUtil.setCurrentUser(request, adminUser);
                }
            }
        }
        chain.doFilter(request, response);
    }
}
